package com.gang.application;

import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.gang.ssm.bos.core.interfaces.IShiro;
import com.gang.ssm.bos.core.shiro.DefaultShiroFactroy;
import com.gang.ssm.bos.core.shiro.ShiroDbRealm;

@Configuration
public class ShiroConfig {

	@Bean
	 public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
		 
	        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
	        shiroFilterFactoryBean.setSecurityManager(securityManager);
	        
	        Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>();
	        
	        filterChainDefinitionMap.put("/static/**", "anon");
	        filterChainDefinitionMap.put("/context/*", "anon");
	        filterChainDefinitionMap.put("/WEB-INF/views/login/login.jsp", "anon");
	        filterChainDefinitionMap.put("/login/checkUser", "anon");
	        filterChainDefinitionMap.put("/login/captcha", "anon");
	        filterChainDefinitionMap.put("/**", "authc");
	        
	        shiroFilterFactoryBean.setLoginUrl("/login/loginUI");
	        shiroFilterFactoryBean.setSuccessUrl("/home.jsp");
	        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorizedUrl.jsp");
	        
	        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
	        return shiroFilterFactoryBean;
	    }

	    @Bean
	    public ShiroDbRealm myShiroRealm(){
	    	ShiroDbRealm myShiroRealm = new ShiroDbRealm();
	    	HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
	    	hashedCredentialsMatcher.setHashAlgorithmName("MD5");
	    	
	    	myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher);
	        return myShiroRealm;
	    }


	    @Bean
	    public SecurityManager securityManager(){
	        DefaultWebSecurityManager securityManager =  new DefaultWebSecurityManager();
	        securityManager.setRealm(myShiroRealm());
	        return securityManager;
	    }
	    
	    @Bean
	    public IShiro getDefaultShiroFactroy() {
	    	return new DefaultShiroFactroy();
	    }
}
